package com.ruoyi.index.userController;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.ruoyi.chat.service.IFhChatFriendService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.index.domain.WeatherDto;
import com.ruoyi.index.service.IWeatherService;
import com.ruoyi.map.domain.*;
import com.ruoyi.map.mapper.FhMapWeatherMapper;
import com.ruoyi.map.service.*;
import com.ruoyi.tokenTools.UserLoginToken;
import com.ruoyi.tools.HttpUtils;
import com.ruoyi.web.core.config.LocalUserInfoUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Api( tags = "获取天气接口")
@RestController
@RequestMapping("/app/weather")
public class WeatherController extends BaseController {

    @Autowired
    private IFhChatFriendService fhChatFriendService;

    @Autowired
    private IFhMapWeatherService fhMapWeatherService;

    @Autowired
    private IFhMapCityCollectService fhMapCityCollectService;

    @Autowired
    private IFhMapWaterService fhMapWaterService;

    @Autowired
    private IFhMapWatercommonfishService fhMapWatercommonfishService;

    @Autowired
    private IFhMapFishtypeService fhMapFishtypeService;

    @Autowired
    private IFhMapFishbaitService fhMapFishbaitService;

    @Autowired
    private IWeatherService weatherService;

    @Autowired
    private FhMapWeatherService tfhMapWeatherService;


    /**
     * 获取天气
     */
    @UserLoginToken
    @ApiOperation("获取天气")
    @GetMapping()
    public R<WeatherDto> list(String lat,String lon) {
        String appcode = "e3761ef60a7e4983a1ae1c87829880d2";
        String host = "https://ali-weather.showapi.com";
        String path = "/gps-to-weather";
        String method = "GET";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("from", "5");
        querys.put("lng", lon);
        querys.put("lat", lat);
        querys.put("needMoreDay", "0");
        querys.put("needIndex", "0");
        querys.put("needHourData", "0");
        querys.put("need3HourForcast", "0");
        querys.put("needAlarm", "0");

        try {
            //发送请求
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            //获取响应实体
            HttpEntity entity = response.getEntity();
            //确保响应实体不为空
            if(entity!=null){
                //将响应实体转换为字符串
                String jsonString = EntityUtils.toString(entity);
                Gson gson = new Gson();
                //解析JSON字符串为JsonObject
                JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
                //提取值
                JsonObject showapiResBody = jsonObject.get("showapi_res_body").getAsJsonObject();
                JsonObject now = showapiResBody.get("now").getAsJsonObject();
                //天气
                String weather = now.get("weather").getAsString();
                //温度
                String temperature = now.get("temperature").getAsString();
                //湿度
                String sd = now.get("sd").getAsString().replace("%", "");  // 去掉百分号;

                JsonObject f1 = showapiResBody.get("f1").getAsJsonObject();
                //日出时间，日落时间
                String sunBeginEnd = f1.get("sun_begin_end").getAsString();
                String weatherCode = now.get("weather_code").getAsString();
                String airPress = f1.get("air_press").getAsString().replace("hPa", "").trim();

                WeatherDto weatherDto = new WeatherDto(weather, temperature, sd,sunBeginEnd,airPress,weatherCode);

//                System.out.println(EntityUtils.toString(response.getEntity()));
                return R.ok(weatherDto);
            }
            return R.fail("获取天气失败");
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }

    }

    @ApiOperation("天气列表")
    @PostMapping("/weatherList")
    public ResponseEntity<Page<FhMapWeather>> weatherList(@RequestBody FhMapWeather query, Pageable page) {
        List<FhMapWeather> list = tfhMapWeatherService.selectList(query, page);
        for (FhMapWeather city : list) {
            fhMapWeatherService.processCityWeather(city);
        }
        return ResponseEntity.ok(new PageImpl<>(list, page, ((com.github.pagehelper.Page)list).getTotal()));
    }

    //天气列表
//    @ApiOperation("天气列表")
//    @GetMapping("/weatherList")
//    public R<List<FhMapWeather>> weatherList(FhMapWeather fhMapWeather) throws IOException {
//        return R.ok(fhMapWeatherService.weatherList(fhMapWeather));
//    }

    //我的天气列表
    @ApiOperation("我的天气列表")
    @GetMapping("/myWeatherList")
    public R<List<FhMapCityCollect>> myWeatherList(FhMapCityCollect fhMapCityCollect) throws IOException {
        return R.ok(fhMapWeatherService.myWeatherList(fhMapCityCollect));
    }


    //删除天气
    @ApiOperation("删除天气")
    @DeleteMapping("/weatherDelete")
    public R<String> weatherDelete(Long id) throws IOException {
        try {
            fhMapWeatherService.weatherDelete(id);
            return R.ok("操作成功");
        }catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    //天气详情
    @ApiOperation("天气详情")
    @GetMapping("/weatherDetails")
    public R<FhMapWeather> weatherDetails(String area) throws IOException {
        return R.ok(fhMapWeatherService.weatherDetails(area));
    }


    //新增天气  天气不保存，只需要新增城市信息就行了
    @ApiOperation("新增天气")
    @PostMapping("/weatherAdd")
    public R<String> weatherAdd(FhMapWeather fhMapWeather){
        try {
            fhMapWeatherService.weatherAdd(fhMapWeather);
            return R.ok("操作成功");
        }catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }


    //此地推荐
    @ApiOperation("此地推荐")
    @GetMapping("/recommendList")
    public TableDataInfo recommendList(String area){
        startPage();
        //获取水域列表
        List<FhMapWater> fhMapWaters = fhMapWaterService.waterRecommendList(area);
        for (FhMapWater fhMapWater : fhMapWaters) {
            //获取天气
            WeatherDto weatherData = fhMapWeatherService.commeonForecast(area);
            fhMapWater.setWaterInfoDto(weatherData);
        }
        return getDataTable(fhMapWaters);

    }


    //新增城市收藏
    @ApiOperation("新增城市收藏")
    @PostMapping("/addCollect")
    public R<String> addCollect(@RequestBody FhMapCityCollect fhMapCityCollect){
        try {
            //获取当前用户id
            Long userId = LocalUserInfoUtil.getLocalUserInfo().getId();
            fhMapCityCollect.setUserId(userId);
            fhMapCityCollectService.addCollect(fhMapCityCollect);
            return R.ok("操作成功");
        }catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }


    //删除城市收藏
    @ApiOperation("删除城市收藏")
    @DeleteMapping("/deleteCollect")
    public R<String> deleteCollect(Long id) throws IOException {
        try {

            fhMapCityCollectService.deleteCollect(id);
            return R.ok("操作成功");
        }catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }


    /**
     * 今日适宜
     */
    @UserLoginToken
    @ApiOperation("今日适宜")
    @GetMapping(value = "/water/{waterId}")
    public R<WaterInfoDto> getWaterInfo(@PathVariable("waterId") Long waterId) {
        try {
            WaterInfoDto waterInfoDto = new WaterInfoDto();

            //水域详情
            FhMapWater fhMapWater = fhMapWaterService.selectFhMapWaterById(waterId);
            waterInfoDto.setFhMapWater(fhMapWater);

            //推荐装备  （查询鱼饵）
            FhMapWatercommonfish fhMapWatercommonfish = new FhMapWatercommonfish();
            fhMapWatercommonfish.setWaterId(waterId);
            List<FhMapWatercommonfish> fhMapWatercommonfishList = fhMapWatercommonfishService.getFhMapWatercommonfish(waterId);
            //循环添加参数
            for (FhMapWatercommonfish mapWatercommonfish : fhMapWatercommonfishList) {
                Long fishId = mapWatercommonfish.getFishId();
                //根据鱼类id查询鱼类信息
                FhMapFishtype fhMapFishtype = fhMapFishtypeService.selectFhMapFishtypeById(fishId);
                //获取鱼饵id
                String baitIds = fhMapFishtype.getBaitIds();
                //分割字符串为ID列表
                List<Long> baitIdList = Arrays.stream(baitIds.split(","))
                        .map(String::trim)  // 去除空格
                        .filter(s -> !s.isEmpty())  // 过滤空值
                        .map(Long::parseLong)  // 转为Long类型
                        .collect(Collectors.toList());
                //根据鱼饵id查询鱼饵信息
                List<FhMapFishbait> baitList = fhMapFishbaitService.selectList(baitIdList);
                mapWatercommonfish.setBaitList(baitList);
            }
            waterInfoDto.setFhMapWatercommonfishList(fhMapWatercommonfishList);

            //获取天气
            WeatherDto weatherData = weatherService.getWeatherData(fhMapWater.getLatitude(), fhMapWater.getLongitude());
            waterInfoDto.setWeatherDto(weatherData);




            return R.ok(waterInfoDto);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }

    }

}
